//
//  VWPlayerNotReachableStateLayer.swift
//  VideoPlayer_Example
//
//  Created by JY_NEW on 2021/10/15.
//  Copyright © 2021 CocoaPods. All rights reserved.
//

import ijkPlayerManager
import UIKit
import UICreate

/// 网络状态
class VWPlayer5GBlockLayer: VWPlayerBaseBlockLayer {
    // 是否允许5G
    var is5GAllowed = false
    
    override func loadPlayerManager(_ player: VideoPlayerManagerType) {
        player.observer.networkStatus.addTarget(self, action: #selector(self.onStatusNetworkChanged))
        player.observer.status.addTarget(self, action: #selector(self.onStatusNetworkChanged))
    }
    override func unloadPlayerManager(_ player: VideoPlayerManagerType) {
        player.observer.networkStatus.removeTarget(self)
        player.observer.status.removeTarget(self)
    }
    
    override func loadContainerView(_ containerView: UIView) {
        containerView.backgroundColor = .black
        containerView.add(self.contentView, layout: .centerY, .marginX)
        
        super.loadContainerView(containerView)
    }
    
    @objc func onStatusNetworkChanged() {
        if self.is5GAllowed { return }
        if let player = self.playerManager {
            //5G并且非离线
            if player.networkStatus == .wwan && !(self.context?.isOffline ?? false) {
                self.active()
            }else {
                self.deactive()
            }
        }
    }
    
    override func show(completion: @escaping () -> Void) {
        self.aniamteShow(for: self.contentView, completion: completion)
    }
    override func hide(completion: @escaping () -> Void) {
        self.aniamteHide(for: self.contentView, completion: completion)
    }
    
    // MARK: 界面控件
    
    lazy var contentView: UIView = {
        let contentView = UIView()
        
        let title = UILabel(.text("当前非WIFI网络，播放\n将产生流量费用哦"), .font(.pingfang(medium: 14)), .color(.white), .lines())
        let button = UIButton(.text("流量播放"), .bg(.white), .size(68, 28), .corner(14), .font(.pingfang(12)), .color(.black), .event(self, #selector(self.onAllow5G)))
        contentView.add {
            title.layout(.top, .centerX)
            button.layout(.bottomTop(18), .centerX)
                .layout(for: .parent, .bottom)
        }
        return contentView
    }()
    
    @objc func onAllow5G() {
        self.is5GAllowed = true
        self.deactive()
    }
}
